import { useState, useEffect } from 'react'

export default function usePetState() {
  const [happiness, setHappiness] = useState(100)
  const [exp, setExp] = useState(0)
  const [level, setLevel] = useState(1)
  const [energy, setEnergy] = useState(100)
  const [action, setAction] = useState('idle')
  const [message, setMessage] = useState('')

  // useEffect(() => {
  //   loadData()
  //   startDecayTimer()
  //   return () => clearInterval(timer)
  // }, [])

  
  useEffect(() => {
    const savedData = localStorage.getItem('virtualPet')
    if (savedData) {
      const { happiness, exp, level, energy } = JSON.parse(savedData)
      setHappiness(happiness)
      setExp(exp)
      setLevel(level)
      setEnergy(energy || 100)
    }

    // 每30分钟降低快乐度和能量
    const timer = setInterval(() => {
      setHappiness(prev => {
        const newHappiness = Math.max(0, prev - 1)
        setEnergy(prevEnergy => {
          const newEnergy = Math.max(0, prevEnergy - 2)
          saveData(newHappiness, exp, level, newEnergy)
          return newEnergy
        })
        return newHappiness
      })
    }, 30 * 60 * 1000)

    return () => clearInterval(timer)
  }, [])


  const loadData = () => {
    const savedData = localStorage.getItem('virtualPet')
    if (savedData) {
      const { happiness, exp, level, energy } = JSON.parse(savedData)
      setHappiness(happiness)
      setExp(exp)
      setLevel(level)
      setEnergy(energy || 100)
    }
  }

  const startDecayTimer = () => {
    const timer = setInterval(() => {
      setHappiness(prev => {
        const newHappiness = Math.max(0, prev - 1)
        setEnergy(prevEnergy => {
          const newEnergy = Math.max(0, prevEnergy - 2)
          saveData(newHappiness, exp, level, newEnergy)
          return newEnergy
        })
        return newHappiness
      })
    }, 30 * 60 * 1000)
    return timer
  }

  const saveData = (happiness, exp, level, energy) => {
    localStorage.setItem('virtualPet', JSON.stringify({ happiness, exp, level, energy }))
  }

  // ... 其他状态管理函数 ...
  const addExp = (amount) => {
    setExp(prev => {
      const newExp = prev + amount
      if (newExp >= level * 100) {
        setLevel(l => {
          const newLevel = l + 1
          setMessage(`升级啦！现在是 ${newLevel} 级了！`)
          setTimeout(() => setMessage(''), 3000)
          saveData(happiness, newExp, newLevel, energy)
          return newLevel
        })
      }
      saveData(happiness, newExp, level, energy)
      return newExp
    })
  }

  return {
    happiness,
    exp,
    level,
    energy,
    action,
    message,
    setMessage,
    setAction,
    setHappiness,
    setEnergy,
    saveData,
    addExp
  }
}